import {sm4, sm3} from 'sm-crypto'
import {Base64} from 'js-base64';


const appId = "202305220944ZY5rcED8Be6";
const appSecret = "Jjnn3c8px3Pd5B25HbpNQF7bPKmSWP6w";

function signNoSalt(data: string, timestamp: string, version: string) {
    const _str = `appid=${appId}&data=${data}&timestamp=${timestamp}`;
    const stringSignTemp = `${_str}&key=${appSecret}&version=${version}`;
    return sm3(stringSignTemp);

}

function stringToHex2(s: string) {
    let r = "";
    const hexes = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"];
    for (let i = 0; i < s.length; i++) {
        r += hexes[s.charCodeAt(i) >> 4] + hexes[s.charCodeAt(i) & 0xf];
    }
    return r;
}

function getHexKey(): string {
    return stringToHex2(appSecret.substring(0, 16));
}

export function encryptByCssd(obj: any): Map<string, string> {
    const jsonString = Base64.encode(JSON.stringify(obj));
    const hexKey = getHexKey();
    const data = sm4.encrypt(jsonString, hexKey);
    const dic = new Map<string, string>();
    dic.set("appid", appId);
    dic.set("data", data);
    dic.set("version", "1.0");
    const timestamp = (new Date().getTime() - new Date(1970, 0, 1, 0, 0, 0, 0).getTime());
    const timestampStr = timestamp.toString();
    dic.set("timestamp", timestampStr);
    const sign = signNoSalt(data, timestampStr, '1.0');
    dic.set("sign", sign);
    return dic;
}

export function decryptByCssd(data: string): string {
    const dataByDecode = sm4.decrypt(data, getHexKey());
    return Base64.decode(dataByDecode);
}



